import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'
import AdminView from '../views/AdminView.vue'

import IndexView from '../components/admin/IndexView.vue'

import AddArticle from '../components/article/AddArticle.vue'
import ArticleList from '../components/article/ArticleList.vue'
import CategoryList from '../components/category/CategoryList.vue'
import TagsList from '../components/tag/TagsList.vue'
import FriendLinkList from '../components/friendlink/FriendLinkList.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: {
      title: '后台登录'
    }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: AdminView,
    children: [
      {
        path: 'index',
        component: IndexView,
        meta: {
          title: '后台主页'
        }
      },
      {
        path: 'addarticle',
        component: AddArticle,
        meta: {
          title: '写文章'
        }
      },
      {
        path: 'addarticle/:id',
        component: AddArticle,
        props: true,
        meta: {
          title: '编辑文章'
        }
      },
      {
        path: 'articlelist',
        component: ArticleList,
        meta: {
          title: '文章列表页'
        }
      },
      {
        path: 'categorylist',
        component: CategoryList,
        meta: {
          title: '分类列表页'
        }
      },
      {
        path: 'tagslist',
        component: TagsList,
        meta: {
          title: '标签列表页'
        }
      },
      {
        path: 'friendlinklist',
        component: FriendLinkList,
        meta: {
          title: '友情链接页'
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const token = window.sessionStorage.getItem('token')
  // 设置网页标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.path === '/login') {
    return next()
  }
  if (!token) {
    next('/login')
  } else {
    next()
  }
})

export default router
